package app

import (
	"common/config"
	"common/discover"
	"common/logs"
	"context"
	"core/repo"
	"net"
	"os"
	"os/signal"
	"syscall"
	"user/internal/server"
	"user/pb"

	"google.golang.org/grpc"
)

func Run(ctx context.Context) error {
	// 初始化日志库，后边logs才能使用
	logs.InitLog(config.Conf.AppName)
	// rpc注册到etcdvs
	register := discover.NewRegister()
	serve := grpc.NewServer()
	lis, err := net.Listen("tcp", config.Conf.Grpc.Addr)
	if err != nil {
		logs.Logger.Fatal("user listener serve start up err," + config.Conf.Grpc.Addr)
	}
	manager := repo.New()
	go func() {
		register.Register(config.Conf.Etcd)
		pb.RegisterUserServiceServer(serve, server.NewAccountServer(manager))
		// 阻塞操作
		err = serve.Serve(lis)
		if err != nil {
			logs.Logger.Fatal("user grpc serve start up err")
		}
	}()

	stop := func() {
		serve.Stop()
		logs.Logger.Info("服务中断")
	}
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGHUP)
	for {
		select {
		case <-ctx.Done():
			stop()
			logs.Logger.Warn("ctx 中断")
			return nil
		case s := <-c:
			switch s {
			case syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT:
				stop()
				logs.Logger.Warn("强制中断")
				return nil
			case syscall.SIGHUP:
				stop()
				logs.Logger.Warn("退出中断")
				return nil
			default:
				logs.Logger.Warn("defualt")
				return nil
			}

		}
	}
}
